package org.huzhp.security;


import org.huzhp.security.wx.WxAuthenticationSecurityConfig;
import org.huzhp.service.IHuzhpUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.client.RestTemplate;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) //启用方法级的权限认证
@Order(1)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private LoginSuccessHandler loginSuccessHandler;

    @Autowired
    private LoginFailureHandler loginFailureHandler;

    @Autowired
    private LogoutSuccessHandler logoutSuccessHandler;

    @Autowired
    private IHuzhpUserService huzhpUserService;


    @Autowired
    private WxAuthenticationSecurityConfig wxAuthenticationSecurityConfig;

    @Override
    protected UserDetailsService userDetailsService() {
        return new BaseUserDetailService(huzhpUserService);
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new Md5PasswordEncoder();
    }


    /**
     * 增加不拦截地址
     *
     * @param web
     */
    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/favicon.ico", "/config/**", "/css/**", "/fonts/**", "/images/**", "/js/**", "/public/**", "/error/**", "/actuator", "/actuator/**");
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.apply(wxAuthenticationSecurityConfig);
        http.headers().frameOptions().disable() //解决iframe嵌套url拒绝问题
                .and().requestMatchers().antMatchers("/login", "/", "/oauth/**")
                .and().formLogin().loginPage("/login").failureHandler(loginFailureHandler).successHandler(loginSuccessHandler).permitAll()
                .and().authorizeRequests().anyRequest().authenticated()
                .and().logout().invalidateHttpSession(true).logoutUrl("/oauth/logout").logoutRequestMatcher(new AntPathRequestMatcher("/oauth/logout", "GET")).logoutSuccessUrl("/login").logoutSuccessHandler(logoutSuccessHandler);

//        http.cors().and().csrf().disable();
        http.cors().and().csrf().ignoringAntMatchers("/oauth/h2-console/login.do");

    }

    /**
     * Spring Boot 2 配置，这里要bean 注入
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate(new SimpleClientHttpRequestFactory());
    }


}
